import {
    serializeGetParams,
    isAbsolutePath
} from '../../util'

const http = require('http')
// import {
//     http
// } from "http"
const https = require('https')
const url = require('url');



function stripBOM(content) {
    if (content.charCodeAt(0) === 0xFEFF) {
        content = content.slice(1);
    }
    return content;
}
export const httpGet = (config) => {
    const _serializeParams = config.data && Object.keys(config.data).length > 0 ? serializeGetParams(config.data.data) : ''
    const _url = config.baseURL.concat(config.url, _serializeParams)
    console.log('_url', _url)
    console.log(config)
    // const parsed = url.parse(_url)
    // console.log('parsed-----parsed', parsed)
    const headers = {
        ...config.headers,
        ...config.data.headers
    }
    const option = {
        method: 'GET',
        // path: config.url + '?configUid=2833992259634716677',
        path: _url,
        headers: headers
    }

    console.log('-------', option)
    const httpModle = config.isHttps ? https : http
    return new Promise((resolve, reject) => {
        const req = httpModle.request(option, res => {
            req.setDefaultEncoding('utf-8')
            let responseBuffer = []
            res.on('data', d => {
                responseBuffer.push(d)
            })
            res.on('end', () => {
                let responseData = Buffer.concat(responseBuffer)
                responseData = stripBOM(responseData.toString("utf-8"))
                resolve(JSON.parse(responseData))
            })
        })
        req.on('error', err => {
            reject(err)
        })
        req.end()
    })

}

export const httpPost = (config) => {
    const data = JSON.stringify(config.data)
    if (config.data) {

    }
    const headers = {
        ...config.headers,
        ...config.data.headers
    }
    const option = {
        method: 'POST',
        // path: config.url + '?configUid=2833992259634716677',
        path: _url,
        headers: headers
    }
    const httpModle = config.isHttps ? https : http
    return new Promise((resolve, reject) => {
        const req = httpModle.request(option, res => {
            req.setDefaultEncoding('utf-8')
            let responseBuffer = []
            res.on('data', d => {
                responseBuffer.push(d)
            })
            res.on('end', () => {
                let responseData = Buffer.concat(responseBuffer)
                responseData = stripBOM(responseData.toString("utf-8"))
                resolve(JSON.parse(responseData))
            })
        })
        req.on('error', err => {
            reject(err)
        })
        req.write(data)
        req.end()
    })
}